package dao;

import model.User;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDao {


    public User login(Connection con, User user) throws Exception {




User resultUser =null;

String sql ="select * from user where username =? and password =? and role =?";

        PreparedStatement preparedStatement =(PreparedStatement) con.prepareStatement(sql);

        preparedStatement.setString(1,user.getUserName());
        preparedStatement.setString(2,user.getPassword());
        preparedStatement.setInt(3,user.getRole());


        ResultSet resultSet = preparedStatement.executeQuery();



        if(resultSet.next()){

            resultUser =new User();
            resultUser.setUserId(resultSet.getInt("id"));
            resultUser.setUserName(resultSet.getString("username"));
            resultUser.setSex(resultSet.getString("sex"));
            resultUser.setPhone(resultSet.getString("phone"));
        }


        return resultUser;


    }





    public int addUser(Connection con, User user) throws Exception{


        String sql ="select * from user where userName =?";

        PreparedStatement pstmt =(PreparedStatement) con.prepareStatement(sql);

        pstmt.setString(1,user.getUserName());

        ResultSet rs = pstmt.executeQuery();

        if(rs.next()){
            return 2;
        }



        String sql1="insert into user(userName,password,role,sex,phone) values(?,?,?,?,?)";

        PreparedStatement pstmt1 = con.prepareStatement(sql1);

        pstmt1.setString(1,user.getUserName());
        pstmt1.setString(2,user.getPassword());
        pstmt1.setInt(3,user.getRole());
        pstmt1.setString(4,user.getSex());
        pstmt1.setString(5,user.getPhone());

        return pstmt1.executeUpdate();

    }



}
